package cn.edu.cqvie.atc.hash.link;

/**
 * 链表，相当于火车
 *
 * @author Zheng Shaohong
 */
public class LinkList {

    // 头节点
    private Node first;

    public LinkList() {
        first = null;
    }

    public LinkList(int maxSize) {
    }

    public LinkList(Node first) {
        this.first = first;
    }

    /**
     * 插入一个节点，在头节点进行插入
     *
     * @param value
     */
    public void insertFirst(Info value) {
        Node node = new Node(value);
        node.next = first;
        first = node;
    }

    /**
     * 删除一个节点，在头节点后进行删除
     */
    public Node deleteFirst() {
        Node tmp = first;
        first = tmp.next;
        return tmp;
    }

    /**
     * 显示方法
     */
    public void display() {
        Node current = first;
        while (current != null) {
            current.display();
            current = current.next;
        }
    }

    /**
     * 查找方法
     * @param key
     * @return
     */
    public Node search(String key) {
        Node current = first;
        while (!key.equals(current.info.getKey())) {
            if (current.next == null) {
                return null;
            }
            current = current.next;
        }
        return current;
    }

    /**
     * 删除方法，根据数据来进行删除
     * @param key
     * @return
     */
    public Node delete(String key) {
        Node current = first;
        Node previous = first;
        while (current.info.getKey() != key) {
            if (current.next == null) {
                return null;
            }
            previous = current;
            current = current.next;
        }
        if (current == first) {
            first = first.next;
        } else {
           previous.next = current.next;
        }
        return current;
    }
}
